package com.example.wm.SanWar.controller;

import java.nio.charset.Charset;

import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReadConfig;
import cn.hutool.core.text.csv.CsvReader;
//import com.csvreader.CsvReader;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.wm.SanWar.VO.InsertCC;
import com.example.wm.SanWar.entity.GameUser;
import com.example.wm.SanWar.entity.Goalgroup;
import com.example.wm.SanWar.entity.GroupTable;
import com.example.wm.SanWar.mapper.GameUserMapper;
import com.example.wm.SanWar.service.AlliesService;
import com.example.wm.SanWar.service.GroupTableService;
import com.example.wm.common.Result;
import com.example.wm.common.ResultData;
import com.example.wm.SanWar.entity.AlliesandUser;

import com.example.wm.SanWar.mapper.AlliesandUserMapper;
import com.example.wm.SanWar.mapper.ConfedrateStaticMapper;
import com.example.wm.SanWar.service.ConfedrateStaticService;
import com.example.wm.utils.CSVUtil;
import com.example.wm.utils.TsyUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.nio.file.Path;
import java.util.*;

//导入记录表
@RestController
@RequestMapping("/ConfedrateStaticController")
public class ConfedrateStaticController {
    @Resource
    private ConfedrateStaticService confedrateStaticService;
    @Resource
    private ConfedrateStaticMapper confedrateStaticMapper;
    @Resource
    private AlliesandUserMapper alliesandUserMapper;
    @Resource
    private GameUserMapper gameUserMapper;
    @Resource
    private TsyUtils tsyUtils;
    @Resource
    private GroupTableService groupTableService;
    @Transactional
    @PostMapping("/insert")
    //日常上传
    public Result insert(@RequestBody InsertCC insertCC){
        LambdaQueryWrapper<GameUser> lq=new LambdaQueryWrapper<>();
        lq.eq(GameUser::getName,insertCC.getGameUser().getName());
       boolean b=  gameUserMapper.exists(lq);



       if(b){
           LambdaQueryWrapper<AlliesandUser> lq1=new LambdaQueryWrapper<>();
           lq1.eq(AlliesandUser::getUserid,gameUserMapper.selectOne(lq).getId());
           lq1.eq(AlliesandUser::getStatus,"在盟");
           lq1.eq(AlliesandUser::getTmid,insertCC.getTmid());
            AlliesandUser one = alliesandUserMapper.selectOne(lq1);
            if (one != null){
                //      更新数据 自己盟里面的数据
                GameUser au = gameUserMapper.selectOne(lq);
                au.setContributeweek(insertCC.getGameUser().getContributeweek());
                au.setMilitaryall(insertCC.getGameUser().getMilitaryall());
                au.setHoldingweek(insertCC.getGameUser().getHoldingweek());
                au.setHoldingall(insertCC.getGameUser().getHoldingall());
                au.setDonationweek(insertCC.getGameUser().getDonationweek());
                au.setDonationall(insertCC.getGameUser().getDonationall());
                au.setSnobbish(insertCC.getGameUser().getSnobbish());
                au.setZone(insertCC.getGameUser().getZone());
                au.setContributeseniority(insertCC.getGameUser().getContributeseniority());
                au.setConntibuteall(insertCC.getGameUser().getConntibuteall());
                au.setMilitaryweek(insertCC.getGameUser().getMilitaryweek());






                int bb= gameUserMapper.updateById(au);
                if(bb>0){
                    return ResultData.success("操作成功");
                }else {
                    return ResultData.error(402,"不成功");

                }
            }else{

                LambdaQueryWrapper<AlliesandUser> lqa=new LambdaQueryWrapper<>();
                lqa.eq(AlliesandUser::getName,insertCC.getGameUser().getName());
                lqa.eq(AlliesandUser::getTmid,insertCC.getTmid());
                lqa.eq(AlliesandUser::getStatus,"已退盟");
                Long g=   alliesandUserMapper.selectCount(lqa);
//            System.out.println(g+"gggg");
                if (g > 0) {

                    if (g > 1) {
                        // 处理多个记录的情况，可以根据业务需求进行调整
                        System.out.println("查询到多条记录，请检查数据完整性");
                        // 可以选择抛出异常或者处理多个记录
                        throw new RuntimeException("查询到多条记录，请检查数据完整性");
                    } else {

                        AlliesandUser auu = alliesandUserMapper.selectOne(lqa);
                        auu.setStatus("在盟");
                        alliesandUserMapper.updateById(auu);
                        GameUser au = gameUserMapper.selectOne(lq);
                        au.setContributeweek(insertCC.getGameUser().getContributeweek());
                        au.setMilitaryall(insertCC.getGameUser().getMilitaryall());
                        au.setHoldingweek(insertCC.getGameUser().getHoldingweek());
                        au.setHoldingall(insertCC.getGameUser().getHoldingall());
                        au.setDonationweek(insertCC.getGameUser().getDonationweek());
                        au.setDonationall(insertCC.getGameUser().getDonationall());
                        au.setSnobbish(insertCC.getGameUser().getSnobbish());
                        au.setZone(insertCC.getGameUser().getZone());
                        au.setContributeseniority(insertCC.getGameUser().getContributeseniority());
                        au.setConntibuteall(insertCC.getGameUser().getConntibuteall());
                        au.setMilitaryweek(insertCC.getGameUser().getMilitaryweek());

                        int bb= gameUserMapper.updateById(au);
                        if(bb>0){
                            return ResultData.success("操作成功");
                        }else {
                            return ResultData.error(402,"不成功");

                        }
                    }
                }else{
//                    该用户不在该同盟内
                    return ResultData.success("操作成功");
                }
            }





       }

//        System.out.println(insertCC.getTmid()+b+insertCC.getGameUser().getName()+"insertCC.getGameUser().getName()");
       else
        {
            HashMap<String,String> hm=new HashMap<>();
            hm.put("新增人员",insertCC.getGameUser().getName());
            insertCC.getGameUser().setRegestertime(tsyUtils.getnowtime());
           int a= gameUserMapper.insert(insertCC.getGameUser());
//            System.out.println("a:"+a);

            //查找盟主的信息
            LambdaQueryWrapper<AlliesandUser> lqa=new LambdaQueryWrapper<>();
            lqa.eq(AlliesandUser::getTmid,insertCC.getTmid());
            lqa.eq(AlliesandUser::getAppoint,"盟主");
            lqa.eq(AlliesandUser::getStatus,"在盟");
            AlliesandUser adu=alliesandUserMapper.selectOne(lqa);
//            System.out.println("adu:"+adu+insertCC.getTmid());
            //插入
            AlliesandUser adua=new AlliesandUser();
            adua.setRegestertime(tsyUtils.getnowtime());
            adua.setStatus("在盟");
            adua.setUserid(insertCC.getGameUser().getId());
            adua.setName(insertCC.getGameUser().getName());
            if(!Objects.equals(insertCC.getGroupname(), adu.getGroupname())){
                hm.put("分组不同",insertCC.getGameUser().getName());
//                System.out.println("分组不同"+insertCC.getGroupname()+adu.getGroupname());
            }else{
                adua.setGroupname(adu.getGroupname());
                adua.setGroupid(adu.getGroupid());
                hm.put("分组不同","无");
//                System.out.println("无");
            }
            adua.setIpaddress(adu.getIpaddress());
            adua.setZone(adu.getZone());
            adua.setCreatename(adu.getName());
            adua.setAppoint("成员");
            adua.setStatus("在盟");
//            adua.setGroupname(adu.getGroupname());
//            adua.setGroupid(adu.getGroupid());
            adua.setAlliasname(adu.getAlliasname());
            adua.setTmid(adu.getTmid());
           int bb= alliesandUserMapper.insert(adua);
            if(bb>0){
                return ResultData.success(hm);
            }else {
                return ResultData.error(405,"不成功");

            }


        }
//        return ResultData.success( "操作成功");


    }
    @Transactional
    @PostMapping("/checkandupdate")
    public Result checkandupdate(@RequestBody JSONObject jsonObject){
//        System.out.println(jsonObject+":jsonObject");
        LambdaQueryWrapper<AlliesandUser> lq=new LambdaQueryWrapper<>();
      List<AlliesandUser> list= alliesandUserMapper.selectList(lq);
        HashSet<String> hs=new HashSet<>();


        for(AlliesandUser a:list){
            hs.add(a.getName());


        }
        // 将数组转换为 HashSet
        // 去掉外层方括号
        String l = jsonObject.getString("List").substring(1, jsonObject.getString("List").length() - 1);
        // 使用逗号分割字符串
        String[] resultArray = l.split(",");
        HashSet<String> hs2=new HashSet<>();
        HashSet<String> hs4=new HashSet<>();

        for (String ss:resultArray){
             ss=ss.trim();
            hs2.add(ss);


        }


        // 计算差集（set1 中有但 set2 中没有的元素）
        hs.removeAll(hs2);

        // 将结果转换为数组 退盟的
        String[] resultArray2 = hs.toArray(new String[0]);


        String[] resultArray5 =hs.toArray(new String[0]);
//        System.out.println(hs4 +"resultArray");
        for (String s:resultArray2){

            LambdaQueryWrapper<AlliesandUser> lqa=new LambdaQueryWrapper<>();
            lqa.eq(AlliesandUser::getName,s);
            lqa.eq(AlliesandUser::getAlliasname,jsonObject.getString("alliasname"));
            lqa.ne(AlliesandUser::getAppoint,"盟主");
            lqa.ne(AlliesandUser::getStatus,"已退盟");
            lqa.ne(AlliesandUser::getStatus,"已拉黑");
//            lqa.ne(AlliesandUser::getStatus,"待审核");

         Long g=   alliesandUserMapper.selectCount(lqa);
//         System.out.println(g+"gggg");
         if(g>0){
             AlliesandUser au=alliesandUserMapper.selectOne(lqa);
             au.setStatus("已退盟");
             alliesandUserMapper.updateById(au);
         }else{
             hs.removeAll(Collections.singleton(s));
             resultArray5 = hs.toArray(new String[0]);


         }


        }

            HashMap<String,List<String>> hsss=new HashMap<>();
            hsss.put("已退盟成员", Arrays.asList(resultArray5));
//            System.out.println(hsss+"hsss");
            return ResultData.success(hsss);







    }

    @Transactional
    @PostMapping("/insertgroup")
    public Result insertgroup( @RequestBody JSONObject jsonObject)  {

        // 去掉外层方括号
        String l = jsonObject.getString("List").substring(1, jsonObject.getString("List").length() - 1);
        // 使用逗号分割字符串
        String[] resultArray = l .split(",");
        LambdaQueryWrapper<GroupTable> gt=new LambdaQueryWrapper<>();
        gt.eq(GroupTable::getTmid,jsonObject.getString("tmid"));
        List<GroupTable> glist=groupTableService.list(gt);

        HashSet<String> hs1=new HashSet<>();
        for (String ss:resultArray){
            ss=ss.trim();
            hs1.add(ss);


        }
         if(!glist.isEmpty()){
             HashSet<String> hs2=new HashSet<>();
             for (GroupTable g:glist){
                 hs2.add(g.getName());

             }
             hs1.removeAll(hs2);
         }

        String[] resultArray5 =hs1.toArray(new String[0]);
        for (String sr : resultArray5) {
            GroupTable gpp = new GroupTable();
            gpp.setTmid(jsonObject.getInteger("tmid"));
            gpp.setCreatename(jsonObject.getString("createname"));
            gpp.setName(sr);
            groupTableService.save(gpp);
        }

        return ResultData.success(hs1);


    }


//    读写表格
@PostMapping("/readerxlsx")
public Result inserttmgxid(@RequestBody MultipartFile file) throws IOException {
    // 获取拥有后缀的文件名 「abc.csv」
    String fileName = file.getOriginalFilename(); // 获取文件名
    // 获取后缀 「abc」
    String fileExtension = null;
    if (fileName != null) {
        fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
    }
    System.out.println(fileExtension + ": fileExtension");

    InputStream is = null;
    // 获取 csv 数据
    if (fileExtension != null && (fileExtension.equals("xlsx") || fileExtension.equals("xls"))) {
        try {
            is = file.getInputStream();
            List<Map> confedrateStaticList = confedrateStaticService.getListByExcel(is, fileName); // 获取解析后的List集合
//            System.out.println(confedrateStaticList.toString());

            return ResultData.success(confedrateStaticList);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else if (fileExtension != null && fileExtension.equals("csv")) {
        // 处理 csv 文件
        try {
            is = file.getInputStream();
//            List<Map> confedrateStaticList = confedrateStaticService.getListByExcel(is, fileName); // 假设有一个方法专门处理 csv 文件
            List<Map<String, String>> csvDataList = new CSVUtil().readCSVFile(is);


            return ResultData.success(csvDataList);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else {
        return ResultData.error(304, "文件错误！");
    }

    return ResultData.error(304, "文件错误！");
}


    public List<Map> submitOriginalFile(MultipartFile file) throws IOException {
        // 拿取前端标识的文件
        // 获取文件流
        InputStream fileIns = file.getInputStream();
//        System.out.println(fileIns+":fileInsfileIns");

        // 获取文件名,中文不乱码写法
//        String name = new String(file.getField("file").getContentDisposition()
//       .getFileName().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        // 将文件流转byte，可作为其他情况存储起来处理
        byte[] fileBytes = InputStreamToByteArray(fileIns);
        // 将byte数组转csv数据
        List<CSVRecord> csvData = byteToCsvFileData(fileBytes);
        // 遍历每一行的数据
        List<Map> list = new ArrayList<>();
        //表头
        List<String> declaredFields = new ArrayList<>();
        for(int j = 0; j < csvData.get(0).size(); j++) {
            declaredFields.add(csvData.get(0).get(j));
//            System.out.println("表头：" + csvData.get(0).get(j));
        }
        // 把需要封装的实体类的属性名存入arrayLis
        List<String> arrayList = new ArrayList<>();
        for (int i = 0; i < declaredFields.size(); i++) {
            if(i==0){
                arrayList.add("成员");
            }else{
                String name = declaredFields.get(i);
                arrayList.add(name.trim());
            }

        }
        for (int i = 0; i < csvData.size(); i++) {
            Map<String, String> map = new HashMap<>();

            if (  csvData.get(i) != null){
//                System.out.println("每一行数据:" + csvData.get(i));
                for(int j = 0; j < csvData.get(i).size(); j++) {
//                    System.out.println("每一行下每一个单元格数据:" + csvData.get(i).get(j));
                    map.put(arrayList.get(j), csvData.get(i).get(j).trim()); // map 封装
                }
                list.add(map);
            }

        }
        return list;

    }

    /**
     * byte转csv数据
     */
    public List<CSVRecord> byteToCsvFileData(byte[] bytes) {
        List<CSVRecord> records = new ArrayList<>();
        try {
            // 将 byte 数组转为 InputStreamReader 对象
            InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(bytes), "UTF-8");
            // 创建csvParser对象
            CSVFormat csvFormat = CSVFormat.EXCEL;
            CSVParser parser = new CSVParser(in, csvFormat);
            // 读取CSV数据行
            records = parser.getRecords();
            parser.close();
            in.close();
        } catch (Exception e) {
            return null;
        }
        return records;
    }

    /**
     * 文件流转byte
     */
    public byte[] InputStreamToByteArray(InputStream inputStream) {
        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer;
            int len;
            byte[] buf = new byte[2048];
            while ((len = bufferedInputStream.read(buf)) != -1) {
                byteArrayOutputStream.write(buf, 0, len);
            }
            byteArrayOutputStream.flush();
            buffer = byteArrayOutputStream.toByteArray();
            inputStream.close();
            bufferedInputStream.close();
            byteArrayOutputStream.close();
            return buffer;
        } catch (Exception e) {
            return null;
        }
    }

    public ArrayList<CsvData> getCsvDataList(MultipartFile multipartFile) throws IOException {
        // 存放所有的 csv 文件数据
        ArrayList<CsvData> csvDataList = new ArrayList<>();

        // 文件的编码，这里设为 utf-8
//        CsvReader reader =new CsvReader();

        CsvReader reader = new CsvReader((Path) multipartFile.getInputStream(), Charset.forName("GB2312"),CsvReadConfig.defaultConfig());

        // 获取数据

            csvDataList.add(reader.read());

        // 关闭
        reader.close();
        return csvDataList;
    }


}
